﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using TfsMerge.BO;
using TfsMerge.Controller;

namespace TfsMerge.View
{
    public partial class HMergeView : BaseDialog
    {
        private readonly HMergeController _controller;

        public IEnumerable<HMergeItem> MergePath { get; private set; }

        public HMergeView(HMergeController controller)
        {
            _controller = controller;

            InitializeComponent();

            memoEdit.Text = string.Empty;

            treeList.FocusedNodeChanged += TreeListFocusedNodeChanged;
            treeList.MouseDoubleClick += TreeListMouseDoubleClick;

            treeList.DataSource = controller.HMergeItems;
            treeList.ExpandAll();
            treeList.BestFitColumns(true);            
        }

        void TreeListFocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            var itm = treeList.GetDataRecordByNode(e.Node) as HMergeItem;
            if (itm == null)
                return;

            memoEdit.Text = string.Join(" -> ",
                _controller.GetPathToPrimary(itm).Select(x => string.Format("{0} ({1})", x.ID, x.ChangesetId)).ToArray());
        }

        void TreeListMouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (treeList.FocusedNode == null)
                return;

            OnOkClick();
        }

        public override void OnOkClick()
        {
            var itm = treeList.GetDataRecordByNode(treeList.FocusedNode) as HMergeItem;
            if (itm == null)
                return;

            var path = _controller.GetPathToPrimary(itm).ToArray();
            if (!_controller.Validate(this, path))
                return;

            MergePath = path;
            base.OnOkClick();
        }
    }
}
